package com.gemme.gemme.gwc;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.pop.CouponPopUtil;
import com.gemme.gemme.util.ActivityCollectorUtil;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.AddressShowView;
import com.gemme.gemme.view.OrderView;
import com.gemme.gemme.view.PayDialog;
import com.gemme.gemme.view.ShopOrderResponse;
import com.gemme.gemme.view.Topview;
import com.gemme.gemme.view.TvTvArrow;
import com.gemme.gemme.wode.AddressBean;
import com.gemme.gemme.wode.AddressNewActivity;
import com.gemme.gemme.wode.DingDanBean;
import com.gemme.gemme.wode.DiscoutBean;
import com.gemme.gemme.wode.ShopOrderInvoice;
import com.gemme.gemme.wode.WoJuanActivity;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ConfirmOrderActivity extends BaseActivity implements View.OnClickListener {

    public static final int code_fapiao = 1000;
    public static final int code_dizhi = 1001;
    public static final int code_zhekoujuan = 1002; //跳转折扣卷
    DingDanBean dingDanBean;
    DiscoutBean.DataBean.RecordsBean juanBean;
    TextView tv_submit;
    TvTvArrow add_address;
    AddressShowView addressView;
    OrderView orderView;
    TvTvArrow tv_zhekoujuan;
    TvTvArrow tv_internal_price;
    TextView tv_pay_price;
    TvTvArrow tv_youhui;
    TvTvArrow tv_fapiao;
    ShopOrderInvoice fpData;
    AddressBean.DataBean addressBean;
    private DecimalFormat mFormat = new DecimalFormat("0.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        ActivityCollectorUtil.addActivity(this);
        initView();
        initTop();
        initData();
    }

    //todo 去除商品id
//    long id;
    private void initData() {
        try {
            Intent intent = getIntent();
            String data = intent.getStringExtra("data");
//todo 去除商品id
//            id = intent.getLongExtra("id",-1);

            dingDanBean = JSON.parseObject(data, DingDanBean.class);
            if (dingDanBean != null)
                setData();
        } catch (Exception e) {

        }
    }

    private void setData() {
        try {
//            dingDanBean.getData().getAddressList().getAddress()
//            add_address.setLeftText(dingDanBean.getData().getAddressList().getAddress() + "");

            /*String addressee = dingDanBean.getData().getAddressList().getAddressee();
            String mobile = dingDanBean.getData().getAddressList().getMobile();
            String address = dingDanBean.getData().getAddressList().getAddress();

            if(!TextUtils.isEmpty(addressee)){
                add_address.setVisibility(View.GONE);
                addressView.setVisibility(View.VISIBLE);
                addressView.setName(addressee).setPhone(mobile).setAdddress(address);
            }
*/
            tv_youhui.setVisibility(View.GONE);
            orderView.setData(dingDanBean.getData().getShopProductVoList());
            orderView.setSumProce(dingDanBean.getData().getPriceSum());
            if(dingDanBean.getData().getVolume()!=null&&dingDanBean.getData().getVolume().size()!=0){
                tv_zhekoujuan.setLeftText("折扣券");
                DingDanBean.DataBean.VolumeBean volumeBean = dingDanBean.getData().getVolume().get(0);
                if (volumeBean.getType()==0){
                    BigDecimal zhekouprice = new BigDecimal(dingDanBean.getData().getPriceSum()).subtract(new BigDecimal(dingDanBean.getData().getPriceSum()).multiply(new BigDecimal(juanBean.getFaceValue()).divide(new BigDecimal(10))));
                    tv_zhekoujuan.setRightText(mFormat.format(zhekouprice));
                }else {
                    if(volumeBean.getCouponType()==0){
                        if(new BigDecimal(dingDanBean.getData().getPriceSum()).compareTo(new BigDecimal(volumeBean.getMeetPrice()))==1){
                            tv_zhekoujuan.setRightText(volumeBean.getCouponFaceValue());
                        }else {
                            tv_zhekoujuan.setRightText("去使用");
                        }
                    }else {
                        tv_zhekoujuan.setRightText(volumeBean.getCouponFaceValue());
                    }
                }
            }else {
                tv_zhekoujuan.setLeftText("折扣券").setRightText("暂无可用");
            }
//            tv_zhekoujuan.setRightText(mFormat.format(getDisCount(dingDanBean)));
            tv_internal_price.setRightText(mFormat.format(dingDanBean.getData().getPriceSum()));
            double pay_price = dingDanBean.getData().getPriceSum() * getDisCount(dingDanBean) / 10;
//            double yhld_price  = dingDanBean.getData().getPriceSum() - pay_price;
            double yhld_price = (new BigDecimal(dingDanBean.getData().getPriceSum())).subtract((new BigDecimal(pay_price))).doubleValue();
            if(tv_zhekoujuan.getRightText().equals("暂无可用")||tv_zhekoujuan.getRightText().equals("去使用")){
                tv_pay_price.setText(mFormat.format(dingDanBean.getData().getPriceSum()));
            }else {
                tv_pay_price.setText(mFormat.format(new BigDecimal(dingDanBean.getData().getPriceSum()).subtract(new BigDecimal(tv_zhekoujuan.getRightText()))));
            }
//            tv_pay_price.setText(mFormat.format(new BigDecimal(pay_price).setScale(4, BigDecimal.ROUND_HALF_UP)));
            tv_youhui.setRightText(mFormat.format(new BigDecimal(yhld_price).setScale(4, BigDecimal.ROUND_HALF_UP)));

        } catch (Exception e) {

        }

    }

    private double getDisCount(DingDanBean dingDanBean) {
        double zhekou = 10.0;

        List<DingDanBean.DataBean.VolumeBean> volume = dingDanBean.getData().getVolume();
        for (int i = 0; i < volume.size(); i++) {
            double faceValue1 = volume.get(i).getFaceValue();
            if (faceValue1 < zhekou) {
                zhekou = faceValue1;
            }
        }
        return zhekou;
    }

    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        Topview topview = findViewById(R.id.topview);
        topview.setContentText("确认订单");
    }

    private void initView() {

        add_address = findViewById(R.id.add_address);
        addressView = findViewById(R.id.addressView);

        orderView = findViewById(R.id.orderView);

        add_address.setLeftText("请添加收货地址");


        tv_fapiao = findViewById(R.id.tv_fapiao);

        tv_youhui = findViewById(R.id.tv_youhui);

        tv_zhekoujuan = findViewById(R.id.tv_zhekoujuan);

        tv_internal_price = findViewById(R.id.tv_internal_price);

        tv_submit = findViewById(R.id.tv_submit);

        tv_pay_price = findViewById(R.id.tv_pay_price);

        tv_fapiao.setLeftText("开具发票");
        tv_youhui.setLeftText("商品优惠力度").setArrowVisble(false);
        tv_internal_price.setLeftText("商品金额").setRightTextColor(Color.parseColor("#ff9c2b2f"));

        add_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, AddressNewActivity.class);
                intent.putExtra("data", code_dizhi);
                startActivityForResult(intent, code_dizhi);
            }
        });

        tv_fapiao.setOnClickListener(this);
        tv_submit.setOnClickListener(this);
        tv_zhekoujuan.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {
            case code_fapiao:
                try {

                    fpData = JSON.parseObject(data.getStringExtra("data"), ShopOrderInvoice.class);
                    String s = fpData.getInvoiceType() == 0 ? "个人" : "企业";
                    String invoiceTitle = fpData.getInvoiceTitle();
                    tv_fapiao.setRightText(s + "-" + invoiceTitle);
                } catch (Exception e) {

                }

                break;

            case code_dizhi:
                try {
                    addressBean = JSON.parseObject(data.getStringExtra("data"), AddressBean.DataBean.class);
                    System.out.println("");
                    String addressee = addressBean.getAddressee();
                    String mobile = addressBean.getMobile();
                    String address = addressBean.getAddress();

                    if (!TextUtils.isEmpty(addressee)) {
                        add_address.setVisibility(View.GONE);
                        addressView.setVisibility(View.VISIBLE);
                        addressView.setName(addressee).setPhone(mobile).setAdddress(address);
                    }
                } catch (Exception e) {

                }

                break;


            case code_zhekoujuan:
                try {
                    juanBean = JSON.parseObject(data.getStringExtra("data"),
                            DiscoutBean.DataBean.RecordsBean.class);
                    if(juanBean!=null){
                        tv_zhekoujuan.setLeftText("折扣券");
                        if (juanBean.getType()==0){
                            BigDecimal zhekouprice = new BigDecimal(dingDanBean.getData().getPriceSum()).subtract(new BigDecimal(dingDanBean.getData().getPriceSum()).multiply(new BigDecimal(juanBean.getFaceValue()).divide(new BigDecimal(10))));
                            tv_zhekoujuan.setRightText(mFormat.format(zhekouprice));
                        }else {
                            if(juanBean.getCouponType()==0){
                                if(new BigDecimal(dingDanBean.getData().getPriceSum()).compareTo(new BigDecimal(juanBean.getMeetPrice()))==1){
                                    tv_zhekoujuan.setRightText(juanBean.getCouponFaceValue());
                                }else {
                                    tv_zhekoujuan.setRightText("去使用");
                                }
                            }else {
                                tv_zhekoujuan.setRightText(juanBean.getCouponFaceValue());
                            }
                        }
                    }else {
                        tv_zhekoujuan.setLeftText("折扣券").setRightText("暂无可用");
                    }

                    if(tv_zhekoujuan.getRightText().equals("暂无可用")||tv_zhekoujuan.getRightText().equals("去使用")){
                        tv_pay_price.setText(mFormat.format(dingDanBean.getData().getPriceSum()));
                    }else {
                        tv_pay_price.setText(mFormat.format(new BigDecimal(dingDanBean.getData().getPriceSum()).subtract(new BigDecimal(tv_zhekoujuan.getRightText()))));
                    }
                } catch (Exception e) {

                }

                break;
        }

    }

    //
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_fapiao:
                /*FaPiaoDialog faPiaoDialog = new FaPiaoDialog();
                faPiaoDialog.showDialog(mContext);*/
                Intent intent = new Intent(mContext, FaPiaoActivity.class);
                if (fpData != null)
                    intent.putExtra("data", JSON.toJSONString(fpData));
                startActivityForResult(intent, code_fapiao);
                break;

            case R.id.tv_submit:
                toserver();
                break;

            case R.id.tv_zhekoujuan:  //跳转折扣卷
                CouponPopUtil couponPopUtil = new CouponPopUtil(tv_zhekoujuan, ConfirmOrderActivity.this);
                couponPopUtil.setPopClickInterface(new CouponPopUtil.PopClickInterface() {
                    @Override
                    public void enterClick(boolean isCoupon) {
                        if (isCoupon) {
                            Intent intent1 = new Intent(mContext, WoJuanActivity.class);
                            intent1.putExtra("pricesum",String.valueOf(dingDanBean.getData().getPriceSum()));
                            startActivityForResult(intent1, code_zhekoujuan);
                        }
                    }
                });
                couponPopUtil.showAtLocation();
                break;
        }
    }

    private void toserver() {

        try {
            ShopOrderResponse shopOrderResponse = new ShopOrderResponse();
            if (addressBean == null || addressBean.getId() == null) {
                Toast.makeText(mContext, "地址不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            //地址ID

            //订单项
            List<ShopOrderResponse.ProductUU> productUU = new ArrayList<>();
            detailOrder(productUU);
            //令牌
            String orderToken = dingDanBean.getData().getOrderToken();

            if (productUU == null || productUU.size() == 0)
                return;

            //优惠卷ID
            Long discountId = null;

            try {
                if (juanBean != null && juanBean.getId() > 0) {
                    discountId = juanBean.getId() + 0L;
                } else {
                    discountId = dingDanBean.getData().getVolume().get(0).getId() + 0L;
                }
            } catch (Exception e) {

            }


            //实际支付价格
            BigDecimal subTotal = new BigDecimal(tv_pay_price.getText() + "");


            shopOrderResponse.setAddressId(new Long(addressBean.getId()));
            shopOrderResponse.setProductUU(productUU);
            shopOrderResponse.setOrderToken(orderToken);
            shopOrderResponse.setDiscountId(discountId);
            shopOrderResponse.setSubTotal(subTotal);

            String json = JSON.toJSONString(shopOrderResponse);
            System.out.println(getComponentName().getClassName() + " : \n" + json);
            String url = DataManager.BaseUrl + "mall/shoporder/submitDiscountCouponsPage";
            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
//        headMap.put(DataManager.AuthorizationKey,"Bearer 2af9350c-dad4-4e04-b5b9-6a931f9b7b0c");
            DataManager.toServer3(mContext, url, DataManager.POST_TYPE, json, headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    try {

                        boolean sucess = DataPares.isSucess(mContext, response);
                        if (sucess) {
                            Toast.makeText(mContext, "提交订单成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext, "提交订单失败", Toast.LENGTH_SHORT).show();
                        }

                        JSONObject jsonObject = new JSONObject(response);
                        String orderCode = jsonObject.getJSONObject("data").getString("orderCode");
                        double orderSubtotal = jsonObject.getJSONObject("data").getDouble("orderSubtotal");
//                       orderSubtotal = 0.01;
//                        finish();
                        System.out.println("");
                        String refundReason = "";
                        String orderDetailId = "";
                        PayDialog payDialog = new PayDialog();
                        payDialog.setData(orderCode, orderSubtotal, refundReason, orderDetailId);

                        OnProductBean onProductBean = new OnProductBean();
                        //todo 去除商品id
//                       onProductBean.setOrderDetailId(id);
                        onProductBean.setOrderSubtotal(orderSubtotal);
                        payDialog.setOnProductBean(onProductBean);
                        payDialog.showDialog(mContext);
/*
                       payDialog.setOnChangeLIstener(new OnChangeLIstener() {
                           @Override
                           public void onChangeLIstener() {
                               */
/*Intent intent = new Intent(mContext, PaySucessActivity.class);

                               intent.putExtra("data",JSON.toJSONString(onProductBean));
                               startActivity(intent);*//*

//                               finish();
                           }
                       });
*/


                    } catch (Exception e) {

                    }
                }
            });
        } catch (Exception e) {

        }


    }

    private void detailOrder(List<ShopOrderResponse.ProductUU> productUU) {
        try {

            List<DingDanBean.DataBean.ShopProductVoListBean> shopProductVoList = dingDanBean.getData().getShopProductVoList();
            for (int i = 0; i < shopProductVoList.size(); i++) {
                DingDanBean.DataBean.ShopProductVoListBean sbean = shopProductVoList.get(i);
                ShopOrderResponse.ProductUU prod = new ShopOrderResponse.ProductUU();
                prod.setCategoryId(sbean.getId() + 0L);
                prod.setUuId(sbean.getUuId());
                prod.setCategoryCount(sbean.getPurchasesNum());
                prod.setAttrName(getName(sbean.getAttributes()));
                prod.setNote("");
                prod.setActiveId(StrUtil.toLong(sbean.getActiveId()));
                if (fpData != null && fpData.getId() != null)
                    prod.setInvoiceId(fpData.getId());
                prod.setProductImage(sbean.getAttributeSpecImage());

                productUU.add(prod);
            }

        } catch (Exception e) {

        }
    }


    private String getName(List<DingDanBean.DataBean.ShopProductVoListBean.AttributesBean> bean) {
        String name = "";
        try {

            for (int i = 0; i < bean.size(); i++) {
                DingDanBean.DataBean.ShopProductVoListBean.AttributesBean pBean = bean.get(i);
                String attributeName = pBean.getAttributeName();
                String attributeSpecName = pBean.getAttributeSpecName();

                if (TextUtils.isEmpty(name)) {
                    name = name + attributeName + "+" + attributeSpecName;
                } else {
                    name = name + "+" + attributeName + "+" + attributeSpecName;
                }

            }
        } catch (Exception e) {

        }

        return name;
    }

}